package projectServlet;

import java.io.IOException;
import java.util.Date;
import java.util.Calendar;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utility.DayspentCal;
import utility.LeaveUtil;

import dao.DAOException;
import dao.EmployeeDAOFactory;
import dao.LeaveDAO;
import dao.LeaveDAOFactory;
import dao.mysql.EmployeeDAOFactoryImpl;
import dao.mysql.LeaveDAOFactoryImpl;
import dto.*;
/**
 * Servlet implementation class ApplyLeave
 *
 * @web.servlet
 *   name="ApplyLeave"
 *   display-name="ApplyLeave"
 *
 * @web.servlet-mapping
 *   url-pattern="/ApplyLeave"
 */
@WebServlet("/ApplyLeave")
public class ApplyLeave extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private int DaysSpent = 0;   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ApplyLeave() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processApply(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processApply(request,response);
		

		
	}
	protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
			
		
	}
	private void processApply(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		//need to get from session
		LeaveDTO leave = new LeaveDTO();
		//int 	userID 	= 1004;
		String SuserID = (String) request.getSession().getAttribute("id");
		int    userID	   = Integer.parseInt(SuserID);
		leave.set_userID(userID);
		
		String	userName; 
		EmployeeDAOFactory eFactory = new EmployeeDAOFactoryImpl();
		UserDTO		user	= new	UserDTO();
		try {
			user	= eFactory.getEmployeeDAO().findUser(userID);
			userName = user.get_name();
			
			leave.set_userName(userName);
		} catch (DAOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		if(!NullInputValidation(request.getParameter("StartYear")) || !NullInputValidation(request.getParameter("StartMonth")) ||
				!NullInputValidation(request.getParameter("StartDay")) ||  !NullInputValidation(request.getParameter("EndYear"))||
				!NullInputValidation(request.getParameter("EndMonth")) ||  !NullInputValidation(request.getParameter("EndDay"))||
				!NullInputValidation(request.getParameter("Reason"))   ||  !NullInputValidation(request.getParameter("WorkDiss")) || 
				!NullInputValidation(request.getParameter("r1"))   ||  !NullInputValidation(request.getParameter("r2")))
		{
			request.getSession().setAttribute("ErrorCaused", true);
			RequestDispatcher rd = request.getRequestDispatcher("/ApplyLeavePreset");
			rd.forward(request, response);
			return;
		}
				
		Calendar cal = Calendar.getInstance();
		
		if(!InputValidation((String)request.getParameter("StartYear"), request.getParameter("StartMonth"), request.getParameter("StartDay") ) || 
				!InputValidation((String)request.getParameter("EndYear"), request.getParameter("EndMonth"), request.getParameter("EndDay") )	)
		{
			request.getSession().setAttribute("ErrorCaused", true);
			RequestDispatcher rd = request.getRequestDispatcher("/ApplyLeavePreset");
			rd.forward(request, response);			
			return;		
		}
		

		cal.set(Integer.parseInt(request.getParameter("StartYear")), Integer.parseInt(request.getParameter("StartMonth")) - 1, Integer.parseInt(request.getParameter("StartDay")));
		Date date = (Date) cal.getTime();
		Calendar cal2 = Calendar.getInstance();
		cal2.set(Integer.parseInt(request.getParameter("EndYear")), Integer.parseInt(request.getParameter("EndMonth")) - 1, Integer.parseInt(request.getParameter("EndDay")));
		Date date2 = (Date) cal2.getTime();
		
		if(!Datevalidation(date,date2))
		{
			request.getSession().setAttribute("ErrorCaused", true);
			RequestDispatcher rd = request.getRequestDispatcher("/ApplyLeavePreset");
			rd.forward(request, response);				
			return;		
		}
		
		if(!EnoughLeaveCheck(user,request.getParameter("selectType"),DayspentCal.CalcDaysSpent(date, date2, LeaveUtil.getDuration(date, date2))))
		{
			request.getSession().setAttribute("ErrorCaused", true);
			RequestDispatcher rd = request.getRequestDispatcher("/ApplyLeavePreset");
			rd.forward(request, response);				
			return;				
		}
			
		leave.set_startDate(date);
		leave.set_endDate(date2);
		leave.set_reason(request.getParameter("Reason"));
		leave.set_workDissemination(request.getParameter("WorkDiss"));
		leave.set_startDateHalfDay(request.getParameter("r1"));
		leave.set_endDateHalfDay(request.getParameter("r2"));
		leave.set_leaveType(request.getParameter("selectType"));
		
		try {
			leave.set_ApprovingManID(eFactory.getEmployeeDAO().findUser(userID).get_supID());
		} catch (DAOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		leave.set_status("Pending");
		leave.set_applicationDate(Calendar.getInstance().getTime());
		
		LeaveDAOFactory leaveDAO = new LeaveDAOFactoryImpl();
		try {
			leaveDAO.getLeaveDAO().applyLeave(leave);
			long LID = leaveDAO.getLeaveDAO().getLastestManipulateRecordID();
			leaveDAO.getLeaveDAO().updateLeaveSpent(DaysSpent, (int)LID);
		} catch (DAOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		request.getSession().setAttribute("ErrorCaused", false);
		RequestDispatcher rd = request.getRequestDispatcher("/ApplyLeavePreset");
		rd.forward(request, response);	
		
	}
	
	private boolean NullInputValidation(String s)
	{
		if(s == null || s.trim() == "")
			return false;
		return true;
	}
	
	private boolean InputValidation(String y,String m,String d)
	{
		if(y.length() != 4 || m.length() > 2 || d.length() > 2)
			return false;
		
		if(!CheckAllNumber(y) || !CheckAllNumber(m) || !CheckAllNumber(d))
			return false;
		
		if(Integer.parseInt(y) > 2012) 
			return false;
		if(Integer.parseInt(m) > 12|| Integer.parseInt(m) < 0)
			return false;
		if(Integer.parseInt(d) > 31 || Integer.parseInt(d) < 0)
			return false;

		return true;
	}
	
	private boolean Datevalidation(Date Startdate,Date EndDay)
	{
		if(Startdate.compareTo( Calendar.getInstance().getTime()) < 0
				|| EndDay.compareTo( Calendar.getInstance().getTime()) < 0)
			return false;
		if(EndDay.compareTo(Startdate) < 0 )
			return false;
		return true;
	}

	private boolean CheckAllNumber(String s)
	{
		for(int i = 0; i < s.length() ;i++)
		{
			if(s.charAt(i) < '0' && s.charAt(i) > '9')
				return false;
		}
		return true;
	}
	
	private boolean EnoughLeaveCheck(UserDTO user,String LeaveType ,int LeaveDays)
	{
		if(LeaveType.equals("Annual"))
		{
			if(user.get_annualLeave() < LeaveDays)
				return false;
		}
		else if(LeaveType.equals("Medical"))
		{
			if(user.get_medicalLeave() < LeaveDays)
				return false;
		}
		else if(LeaveType.equals("Compensation"))
		{
			if(user.get_compensationLeave() < LeaveDays)
				return false;
		}
		DaysSpent = LeaveDays;
		return true;
	}
	
}

